import json
import re

from django.http import JsonResponse
from django.views import View
from django_redis import get_redis_connection

from apps.goods.models import SKU
from apps.users.models import User


# Create your views here.

class UsernameCountView(View):
    def get(self, request, username):
        count = User.objects.filter(username=username).count()
        return JsonResponse({'code': 0,'count':count,'errmsg':'ok'})

class MobileCountView(View):
    def get(self, request, mobile):
        count = User.objects.filter(mobile=mobile).count()
        return JsonResponse({'code': 0,'count':count,'errmsg':'ok'})

class RegisterView(View):
    def post(self, request):
        body_bytes = request.body
        body_str = body_bytes.decode()
        body_dict = json.loads(body_str)

        username = body_dict.get('username')
        password = body_dict.get('password')
        password2 = body_dict.get('password2')
        mobile = body_dict.get('mobile')
        allow = body_dict.get('allow')

        if not all([username, password, password2, mobile, allow]):
            return JsonResponse({'code': 400, 'errmsg': '缺少参数'})
        if not re.match('^.[a-zA-Z0-9_-]{5,20}$', username):
            return JsonResponse({'code': 400, 'errmsg': '用户名格式错误'})
        if not re.match('^.{8,20}$', password):
            return JsonResponse({'code': 400, 'errmsg': '密码格式错误'})
        if password != password2:
            return JsonResponse({'code': 400, 'errmsg': '两次密码输入不一致'})
        if not re.match('^1[3-9]\d{9}$', mobile):
            return JsonResponse({'code': 400, 'errmsg': '手机号格式错误'})
        if not allow:
            return JsonResponse({'code': 400, 'errmsg': '请同意用户协议'})

        # User.objects.create(username=username, password=password, mobile=mobile)
        user = User.objects.create_user(username=username, password=password, mobile=mobile)

        # 登录状态保持
        from django.contrib.auth import login

        login(request, user)

        return JsonResponse({'code': 0, 'errmsg': '注册成功'})

class LoginView(View):
    def post(self,request):
        data = json.loads(request.body.decode())
        username = data.get('username')
        password = data.get('password')
        remembered = data.get('remembered')

        if not all([username,password]):
            return JsonResponse({'code':400,'errmsg':'缺少参数'})

        if re.match('^1[3-9]\d{9}$',username):
            User.USERNAME_FIELD='mobile'
        else:
            User.USERNAME_FIELD='username'


        from django.contrib.auth import authenticate,login

        user = authenticate(request,username=username,password=password)

        if user is None:
            return JsonResponse({'code':400,'errmsg':'用户名或密码错误'})
        login(request,user)
        # print("登录会话已创建，session_id:", request.session.session_key)

        if remembered:
            request.session.set_expiry(None)
        else:
            request.session.set_expiry(0)

        response = JsonResponse({'code':0,'errmsg':'登录成功'})
        response.set_cookie('username',username, domain='.meiduo.site')

        from apps.carts.utils import merge_cookie_to_redis
        response = merge_cookie_to_redis(request,response)
        return response

class LogoutView(View):
    def delete(self,request):

        from django.contrib.auth import logout
        logout(request)
        response = JsonResponse({'code':0,'errmsg':'退出成功'})
        response.delete_cookie('username')
        return response

from utils.views import LoginRequiredJsonMixin
class CenterView(LoginRequiredJsonMixin,View):

    def get(self, request):

        info_data = {
            'username':request.user.username,
           'mobile':request.user.mobile,
            'email':request.user.email,
            'email_active':request.user.email_active
        }
        return JsonResponse({'code':0,'errmsg':'ok','info_data':info_data})

class EmailView(LoginRequiredJsonMixin,View):

    def put(self,request):

        data = json.loads(request.body.decode())
        email = data.get('email')
        user = request.user
        user.email = email
        user.save()
        # from django.core.mail import send_mail
        subject = '美多商城激活邮件'
        message =""
        from_email = '美多商城<18027417187@163.com>'
        recipient_list = [email,'18027417187@163.com']
        #加密激活链接
        from apps.users.utils import generic_email_verify_token
        token = generic_email_verify_token(request.user.id)
        # html_message = "点击此链接激活你的美多商城账号 <a href='http://itcast.cn/?token=%s'>激活链接</a>"%token
        verify_url = 'http://www.meiduo.site:8080/success_verify_email.html?token=%s' % token
        html_message = '<p>尊敬的用户您好！</p>' \
                       '<p>感谢您使用美多商城。</p>' \
                       '<p>您的邮箱为：%s 。请点击此链接激活您的邮箱：</p>' \
                       '<p><a href="%s">%s<a></p>' % (email, verify_url, verify_url)

        from celery_tasks.email.tasks import celery_send_email
        celery_send_email.delay(subject=subject,
                                message=message,
                                from_email=from_email,
                                recipient_list=recipient_list,
                                html_message=html_message)
        # send_mail(subject=subject,
        #           message=message,
        #           from_email=from_email,
        #           recipient_list=recipient_list,
        #           html_message=html_message)
        return JsonResponse({'code':0,'errmsg':'ok'})

class EmailVerifyView(View):

    def put(self,request):
        params = request.GET
        token = params.get('token')
        if token is None:
            return JsonResponse({'code':400,'errmsg':'缺少token'})
        from apps.users.utils import check_verify_token
        user_id = check_verify_token(token)
        if user_id is None:
            return JsonResponse({'code':400,'errmsg':'token无效'})
        user = User.objects.get(id=user_id)
        user.email_active = True
        user.save()
        return JsonResponse({'code':0,'errmsg':'ok'})

from apps.users.models import Address

class AddressCreateView(LoginRequiredJsonMixin,View):

    def post(self,request):

        count = request.user.addresses.count()
        if count >= 20:
            return JsonResponse({'code':400,'errmsg':'地址数量已达到上限'})

        data = json.loads(request.body.decode())
        receiver = data.get('receiver')
        province_id = data.get('province_id')
        city_id = data.get('city_id')
        district_id = data.get('district_id')
        place = data.get('place')
        mobile = data.get('mobile')
        tel = data.get('tel')
        email = data.get('email')
        user = request.user

        if not all([receiver,province_id,city_id,district_id,place,mobile]):
            return JsonResponse({'code':400,'errmsg':'缺少必传参数'})
        if not re.match(r'^1[3-9]\d{9}$', mobile):
            return JsonResponse({'code':400,'errmsg':'手机号格式错误'})
        if tel:
            if not re.match(r'^(0[0-9]{2,3}-)?([2-9][0-9]{6,7})+(-[0-9]{1,4})?$', tel):
                return JsonResponse({'code':400,'errmsg':'固定电话格式错误'})
        if email:
            if not re.match(r'^[a-z0-9][\w.\-]*@[a-z0-9\-]+(\.[a-z]{2,5}){1,2}$', email):
                return JsonResponse({'code':400,'errmsg':'邮箱格式错误'})

        try:
            address = Address.objects.create(
                user=user,
                title=receiver,
                receiver=receiver,
                province_id=province_id,
                city_id=city_id,
                district_id=district_id,
                place=place,
                mobile=mobile,
                tel=tel,
                email=email
            )
            if not request.user.default_address:
                request.user.default_address = address
                request.user.save()
        except Exception as e:
            return JsonResponse({'code':400,'errmsg':'新增地址失败'})

        address_dict = {
            "id": address.id,
            "title": address.title,
            "receiver": address.receiver,
            "province": address.province.name,
            "city": address.city.name,
            "district": address.district.name,
            "place": address.place,
            "mobile": address.mobile,
            "tel": address.tel,
            "email": address.email
        }
        return JsonResponse({'code':0,'errmsg':'ok','address':address_dict})

class AddressView(LoginRequiredJsonMixin,View):

    def get(self,request):
        user = request.user
        addresses = Address.objects.filter(user=request.user,is_deleted=False)
        address_list = []
        for address in addresses:
            address_list.append({
                "id": address.id,
                "title": address.title,
                "receiver": address.receiver,
                "province": address.province.name,
                "city": address.city.name,
                "district": address.district.name,
                "place": address.place,
                "mobile": address.mobile,
                "tel": address.tel,
                "email": address.email
            })
        return JsonResponse({'code':0,'errmsg':'ok','addresses':address_list})

class UpdateDestroyAddressView(LoginRequiredJsonMixin,View):

    def put(self,request,address_id):
        data = json.loads(request.body.decode())
        receiver = data.get('receiver')
        province_id = data.get('province_id')
        city_id = data.get('city_id')
        district_id = data.get('district_id')
        place = data.get('place')
        mobile = data.get('mobile')
        tel = data.get('tel')
        email = data.get('email')
        user = request.user

        if not all([receiver,province_id,city_id,district_id,place,mobile]):
            return JsonResponse({'code':400,'errmsg':'缺少必传参数'})
        if not re.match(r'^1[3-9]\d{9}$', mobile):
            return JsonResponse({'code':400,'errmsg':'手机号格式错误'})
        if tel:
            if not re.match(r'^(0[0-9]{2,3}-)?([2-9][0-9]{6,7})+(-[0-9]{1,4})?$', tel):
                return JsonResponse({'code':400,'errmsg':'固定电话格式错误'})
        if email:
            if not re.match(r'^[a-z0-9][\w.\-]*@[a-z0-9\-]+(\.[a-z]{2,5}){1,2}$', email):
                return JsonResponse({'code':400,'errmsg':'邮箱格式错误'})

        try:
            address = Address.objects.get(id=address_id)
            address.title = receiver
            address.receiver = receiver
            address.province_id = province_id
            address.city_id = city_id
            address.district_id = district_id
            address.place = place
            address.mobile = mobile
            address.tel = tel
            address.email = email
            address.save()
        except Exception as e:
            return JsonResponse({'code':400,'errmsg':'更新地址失败'})

        address_dict = {
            "id": address.id,
            "title": address.title,
            "receiver": address.receiver,
            "province": address.province.name,
            "city": address.city.name,
            "district": address.district.name,
            "place": address.place,
            "mobile": address.mobile,
            "tel": address.tel,
            "email": address.email
        }
        return JsonResponse({'code':0,'errmsg':'ok','address':address_dict})

    def delete(self,request,address_id):
        try:
            address = Address.objects.get(id=address_id)
            address.is_deleted = True
            address.save()
        except Exception as e:
            return JsonResponse({'code':400,'errmsg':'删除地址失败'})
        return JsonResponse({'code':0,'errmsg':'ok'})

class DefaultAddressView(LoginRequiredJsonMixin,View):

    def put(self,request,address_id):
        try:
            address = Address.objects.get(id=address_id)
            request.user.default_address = address
            request.user.save()
        except Exception as e:
            return JsonResponse({'code':400,'errmsg':'设置默认地址失败'})
        return JsonResponse({'code':0,'errmsg':'ok'})

class UpdateTitleAddressView(LoginRequiredJsonMixin,View):

    def put(self,request,address_id):
        data = json.loads(request.body.decode())
        title = data.get('title')
        try:
            address = Address.objects.get(id=address_id)
            address.title = title
            address.save()
        except Exception as e:
            return JsonResponse({'code':400,'errmsg':'设置地址标题失败'})
        return JsonResponse({'code':0,'errmsg':'ok'})

class ChangePasswordView(LoginRequiredJsonMixin,View):

    def put(self,request):
        data = json.loads(request.body.decode())
        old_password = data.get('old_password')
        new_password = data.get('new_password')
        new_password2 = data.get('new_password2')

        if not all([old_password,new_password,new_password2]):
            return JsonResponse({'code':400,'errmsg':'缺少必传参数'})
        if not re.match('^.{8,20}$', new_password):
            return JsonResponse({'code':400,'errmsg':'密码格式错误'})
        if new_password != new_password2:
            return JsonResponse({'code':400,'errmsg':'两次密码输入不一致'})

        user = request.user
        if not user.check_password(old_password):
            return JsonResponse({'code':400,'errmsg':'旧密码错误'})

        user.set_password(new_password)
        user.save()
        return JsonResponse({'code':0,'errmsg':'ok'})

class UserHistoryView(LoginRequiredJsonMixin,View):

    def post(self,request):
        user = request.user

        data = json.loads(request.body.decode())
        sku_id = data.get('sku_id')
        try:
            sku = SKU.objects.get(id=sku_id)
        except SKU.DoesNotExist:
            return JsonResponse({'code':400,'errmsg':'没有此商品'})

        redis_cli = get_redis_connection('history')
        redis_cli.lrem('history_%s'%user.id,0,sku_id)
        redis_cli.lpush('history_%s'%user.id,sku_id)
        redis_cli.ltrim('history_%s'%user.id,0,4)

        return JsonResponse({'code':0,'errmsg':'ok'})

    def get(self,request):
        redis_cli = get_redis_connection('history')
        ids = redis_cli.lrange('history_%s'%request.user.id,0,4)
        skus = []
        for sku_id in ids:
            sku = SKU.objects.get(id=sku_id)
            skus.append({
                'id': sku.id,
                'name': sku.name,
                'default_image_url': sku.default_image.url,
                'price': sku.price
            })

        return JsonResponse({'code':0,'errmsg':'ok','skus':skus})